#! /usr/bin/perl

use strict;
use Net::SMTP;
use Authen::SASL;

sub get_today
{ 
	my($sec, $min, $hour, $day, $month, $year) = localtime(time());
	$year += 1900;
	$month++;
	my $today = sprintf("%04d%02d%02d", $year, $month, $day);
	return $today;
}

# mail_user should be your_mail@hbgk.net
sub send_mail
{
	my $mail_user = "SvnBackup";
	my $mail_rcpt = "xwli\@hbgk.net";
	my $mail_cc = "xwli\@hbgk.net";
	my $mail_server = "192.168.0.1";
	my $mail_subject = "Subject: SVN Backup Check Results\n";

	open(SESAME, "./report") || die "can not open ./report";
	my @mail_content = <SESAME>;
	close(SESAME);

	my $smtp = Net::SMTP->new($mail_server);

	#$smtp->auth($mail_user, $mail_pwd) || die "Auth Error! $!";
	$smtp->mail($mail_user);
	$smtp->to($mail_rcpt);
	$smtp->cc($mail_cc);

	$smtp->data();
	$smtp->datasend("From: $mail_user\n");
	$smtp->datasend("To: $mail_rcpt\n");
	$smtp->datasend("Cc: $mail_cc\n");
	$smtp->datasend($mail_subject);
	$smtp->datasend("\n");
	foreach my $tmp_content (@mail_content)
	{
		print $tmp_content;
		$smtp->datasend($tmp_content);
	}
	$smtp->dataend();

	$smtp->quit();
}

# defined the var
my $bak_dir = "/home/www/svn_backup/";
my $src_dir = "/home/www/svn_repos/";
my @repos = ("nvr", "trac");
my $title_cmd = "echo \"The following is the contrast between the result and the real database backup last night, if given the backup version number, said backup successfully; if you give error messages or no backup version number, said backup failed:\n\" >./report";

system $title_cmd || die "exec failed/n";

foreach my $tmp_repos(@repos)
{
	my $tmp_bak_dir	= $bak_dir.$tmp_repos."/".&get_today;
	
	if (-e $tmp_bak_dir)
	{
		my $tmp_src_dir	= $src_dir."/".$tmp_repos;
		my $body_cmd = "echo \"=========================================================================\" >>./report";
		my $bottom_cmd = "echo \"The backup location: From ".$tmp_bak_dir."\" >>./report";
		my $tmp_bak_cmd	= "echo \"Last night the backup version is: \" >>./report; svnlook youngest ".$tmp_bak_dir." >>./report 2>&1";
		my $tmp_src_cmd	= "echo \"The latest version and last modification time is real in the library: \" >>./report; svnlook youngest ".$tmp_src_dir." >>./report 2>&1; echo \"\n\" >>./report";
		
		system $body_cmd || die "exec failed/n";
		system $bottom_cmd || die "exec failed/n";
		system $tmp_bak_cmd || die "exec failed/n";
		system $tmp_src_cmd || die "exec failed/n";
	}
}

&send_mail;
